package com.lsa.letcode.the113.pathSumII;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import com.lsa.letcode.common.TreeNode;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
    	List<List<Integer>> result = new ArrayList<List<Integer>>();
    	pathSums(root, new LinkedList<Integer>(), sum, result);
        return result;
    }
    
    private void pathSums(TreeNode root, LinkedList<Integer> cur, int sum, List<List<Integer>> result) {
    	if (root == null){
        	return;
        }
        else {
        	int curSum = sum - root.val;
        	cur.addFirst(root.val);
        	if (root.left == null && root.right == null && curSum == 0){
        		List<Integer> l = new ArrayList<Integer>(cur);
        		Collections.reverse(l);
        		result.add(l);
        	}
        	else {
        		pathSums(root.left, cur, curSum, result);
        		pathSums(root.right, cur, curSum, result);
        	}
        	cur.removeFirst();
        }
    }
}